<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-col>
                    <el-alert type="info" center show-icon :closable="false">修改商品信息</el-alert>
                </el-col>
            </el-row>
            <el-steps :space="400" :active="activeStep-0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" label-position="top">
                <el-tabs tab-position="left" v-model="activeStep" :before-leave="next" @tab-click="tabClick">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item prop="goods_name" label="商品名称">
                            <el-input v-model="editForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item prop="goods_price" label="商品价格">
                            <el-input v-model.number="editForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item prop="goods_weight" label="商品重量">
                            <el-input v-model.number="editForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item prop="goods_number" label="商品数量">
                            <el-input v-model.number="editForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                    v-model="selectedKeys"
                                    :options="cateList"
                                    :props="cateProps"
                                    @change="handleChange"></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox :label="child" v-for="(child,i) in item.attr_vals" border
                                             :key="i"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :key="item.attr_id" :label="item.attr_name" v-for="item in onlyTableData">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                                :action="uploadURL"
                                :on-success="handleSuccess"
                                :on-preview="handlePreview"
                                :on-remove="handleRemove"
                                list-type="picture"
                                :headers="headerObj"
                        >
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="editForm.goods_introduce">
                        </quill-editor>
                        <el-button type="primary" class="editGoods" @click="edit('editFormRef')">更新商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <el-dialog
                title="图片预览"
                :visible.sync="previewDialogVisible"
                width="50%"
        >
            <img :src="fileURL" alt="" class="preivewImg">
        </el-dialog>
    </div>
</template>

<script>
  import Vue from 'vue';
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import VueQuillEditor from "vue-quill-editor";
  Vue.use(window.VueQuillEditor);
  export default {
    name: "Edit",
    data(){
      return {
        activeStep: '0',
        editForm: {
          goods_name: '',
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          goods_cat: '',
          goods_introduce: '',
          attrs: [],
          pics: [],
        },
        editFormRules: {
          goods_name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'}
          ],
          goods_price: [
            {required: true, message: '请输入商品价格', trigger: 'blur'}
          ],
          goods_weight: [
            {required: true, message: '请输入商品重量', trigger: 'blur'}
          ],
          goods_number: [
            {required: true, message: '请输入商品数量', trigger: 'blur'}
          ],
          goods_cat: [
            {required: true, message: '请输入商品分类', trigger: 'blur'}
          ],

        },
        cateList: [],
        cateProps: {
          expandTrigger: 'hover',
          label: 'cat_name',
          value: 'cat_id',
          children: 'children'
        },
        selectedKeys: [],
        manyTableData: [],
        onlyTableData: [],
        uploadURL: 'http://localhost:8888/api/private/v1/upload',
        previewDialogVisible: false,
        headerObj: {
          authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE2MTgzODYyMTksImV4cCI6MTYxODQ3MjYxOX0.QNw2YgV-hzddOsHwGHs2Z15lQbiuSmaPowJr7XzQwMI'
        },
        fileURL: '',
        goodsData:{}
      }
    },
    created() {
      this.getCateList();
      this.getGoodsData();
    },
    methods:{
      async getGoodsData(){
        const {data:res} = await this.$http({
          url:"goods/"+window.sessionStorage.getItem('id'),
          method:'get',
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取商品数据失败');
        this.goodsData = res.data;
        this.editForm.goods_name = this.goodsData.goods_name;
        this.editForm.goods_price = this.goodsData.goods_price;
        this.editForm.goods_weight = this.goodsData.goods_weight;
        this.editForm.goods_number = this.goodsData.goods_number;
        this.editForm.goods_introduce = this.goodsData.goods_introduce;
        this.editForm.pics = [{"pic":this.goodsData.pics[0]["pics_mid"]}];
        this.editForm.goods_cat = this.goodsData.goods_cat;
        this.selectedKeys = this.editForm.goods_cat.split(',');
        this.selectedKeys.forEach((value,i,arr) => {
          arr[i] = value - 0;
        });
      },
      async getCateList() {
        const {data: res} = await this.$http({
          url: 'categories',
          method: 'get'
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取分类数据失败');
        this.cateList = res.data;
      },
      handleChange() {
        if (this.selectedKeys.length === 3) {
          this.editForm.goods_cat = this.selectedKeys.join(',');
        } else {
          this.selectedKeys = [];
        }
      },
      next(activeName, oldActiveName) {
        if (activeName !== '0' && oldActiveName === '0') {
          if (this.selectedKeys.length === 0) {
            this.$message.error('请选择商品分类');
            return false;
          }
          return true;
        }
      },
      async tabClick() {
        if (this.activeStep === '1') {
          const {data: res} = await this.$http({
            url: `categories/${this.cateId}/attributes`,
            method: 'get',
            params: {sel: 'many'}
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error('获取动态参数失败');
          res.data.forEach((item) => {
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',');
          });
          this.manyTableData = res.data;
        } else if (this.activeStep === '2') {
          const {data: res} = await this.$http({
            url: `categories/${this.cateId}/attributes`,
            method: 'get',
            params: {sel: 'only'}
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error('获取静态属性失败');
          this.onlyTableData = res.data;
        }
      },
      handleSuccess(response) {
        if (response.meta.status === 403) return this.$message.error(response.meta.msg);
        if (response.meta.status !== 200) return this.$message.error('图片上传失败');
        this.editForm.pics.push({"pic": response.data.tmp_path});
        this.$message.success('图片上传成功');
      },
      handlePreview(file) {
        this.fileURL = file.response.data.url;
        this.previewDialogVisible = true;
      },
      handleRemove(file) {
        let filePath = file.response.data.tmp_path;
        let index = this.editForm.pics.findIndex(x => {
          return x.pic === filePath;
        });
        this.editForm.pics.splice(index, 1);

      },
      edit(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (!valid) return this.$message.error('表单不合法');
          this.manyTableData.forEach(item => {
            let newInfo = {};
            newInfo.attr_id = item.attr_id;
            newInfo.attr_value = item.attr_vals.join(',');
            this.editForm.attrs.push(newInfo);
          });
          this.onlyTableData.forEach(item => {
            let newInfo = {};
            newInfo.attr_id = item.attr_id;
            newInfo.attr_value = item.attr_vals;
            this.editForm.attrs.push(newInfo);
          });
          const {data:res} = await this.$http({
            url:'goods',
            method:'post',
            data:this.editForm
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 201) return this.$message.error('更新商品失败');
          this.$message.success('更新商品成功');
          this.$router.push('/goods');
        });
      }
    },
    computed: {
      cateId() {
        if (this.selectedKeys.length === 3) {
          return this.selectedKeys[2];
        }
      }
    },
  }
</script>

<style scoped>
    .preivewImg {
        width: 100%;
        height: 500px;
    }

    .el-breadcrumb {
        margin-bottom: 20px;
    }

    .el-steps {
        margin: 15px 0;
    }

    .el-checkbox {
        margin: 0 10px 0 0 !important;
    }

    .editGoods {
        margin-top: 10px;
    }
</style>